package com.erp.common.utils;

import com.erp.common.config.KpjdConfig;
import com.erp.common.mail.EmailBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * @Auther: Eric
 * @Date: 2019-11-07 11:16
 * @Description:
 */
@Component
public class EmailHelper {

    @Autowired
    private KpjdConfig kpjdConfig;

    @Resource
    private JavaMailSender javaMailSender;

    private static EmailHelper INSTANCE;

    public EmailHelper() {
        INSTANCE = this;
    }

    public static EmailHelper getInstance(){
        return INSTANCE;
    }

    /**
     * 发送一封简单的文本文件
     * @param emailBean 文件内容
     * @return
     */
    public R sendSimpleMail(EmailBean emailBean) {
        System.out.println("==开始发送邮件, Subject: "+emailBean.getSubject()+", setTo:"+emailBean.getToEmail());

        String nick="";
        try {
            nick=javax.mail.internet.MimeUtility.encodeText("ROC科鹏机电");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
//            helper.setFrom(emailBean.getFromEmail());
            helper.setFrom(new InternetAddress(nick+" <"+emailBean.getFromEmail()+">"));
            helper.setTo(emailBean.getToEmail());
            helper.setSubject(emailBean.getSubject());
            helper.setText(emailBean.getText());
        } catch (MessagingException e) {
            System.out.println("==邮件发送失败"+e.getMessage());
            return R.error();
        }
        try {
            javaMailSender.send(mimeMessage);
            System.out.println("==邮件发送成功, Subject:"+emailBean.getSubject()+", setTo:"+ emailBean.getToEmail());
            return R.ok();
        } catch (Exception e) {
            System.out.println("==邮件发送失败"+e.getMessage());
            return R.error();
        }
    }


    /**
     * 发送一封带附件的邮件
     * @param emailBean 文件内容
     * @return
     */
    public R sendAttachmentsMail(EmailBean emailBean) {
        System.out.println("==开始发送邮件, Subject: "+emailBean.getSubject()+", setTo:"+emailBean.getToEmail());

        String nick="";
        try {
            nick=javax.mail.internet.MimeUtility.encodeText("ROC科鹏机电");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
//            helper.setFrom(emailBean.getFromEmail());
            helper.setFrom(new InternetAddress(nick+" <"+emailBean.getFromEmail()+">"));
            helper.setTo(emailBean.getToEmail());
            helper.setSubject(emailBean.getSubject());
            helper.setText(emailBean.getText());
            if (!CollectionUtils.isEmpty(emailBean.getEmailAttachment())) {
                emailBean.getEmailAttachment().stream().filter(Objects::nonNull).forEach(bean -> {
                    try{
                        File file = ResourceUtils.getFile(kpjdConfig.getUploadPath()+bean.getFileName());
                        helper.addAttachment(bean.getFileName(), file);
                    }catch (Exception e){
                        System.out.println("==添加附件失败, filename:"+bean.getFileName()+", filePath:"+bean.getFilePath());
                        e.printStackTrace();
                    }
                });
            }
        } catch (MessagingException e) {
            System.out.println("==邮件发送失败"+e.getMessage());
            return R.error();
        }
        try {
            javaMailSender.send(mimeMessage);
            System.out.println("==邮件发送成功, Subject:"+emailBean.getSubject()+", setTo:"+emailBean.getToEmail());
            return R.ok();
        } catch (Exception e) {
            System.out.println("==邮件发送失败"+e.getMessage());
        }
        return R.error();
    }

    /**
     * 发送一封嵌入静态资源的邮件
     * @param emailBean 文件内容
     * @return
     */
    public R sendInlineMail(EmailBean emailBean) {
//        log.info("==开始发送邮件, Subject: {}, setTo:{}", emailBean.getSubject(), emailBean.getToEmail());
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(emailBean.getFromEmail());
            helper.setTo(emailBean.getToEmail());
            helper.setSubject(emailBean.getSubject());
            helper.setText(emailBean.getText(), true);
            // 注意addInline()中资源名称 hello 必须与 text正文中cid:hello对应起来
            FileSystemResource file = new FileSystemResource(new File(emailBean.getInlineFile().getFilePath()));
            helper.addInline(emailBean.getInlineFile().getContentId(), file);
        } catch (MessagingException e) {
//            log.error("==邮件发送失败", e);
            return R.error();
        }
        try {
            javaMailSender.send(mimeMessage);
//            log.info("==邮件发送成功, Subject: {}, setTo:{}", emailBean.getSubject(), emailBean.getToEmail());
            return R.ok();
        } catch (Exception e) {
//            log.error("==邮件发送失败", e);
        }
        return R.error();
    }

    /**
     * 发送一封模板邮件
     * @param emailBean 文件内容
     * @return
     */
    public R sendTemplateMail(EmailBean emailBean) {
        System.out.println("==开始发送邮件, Subject: "+ emailBean.getSubject()+", setTo:"+emailBean.getToEmail());
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(emailBean.getFromEmail());
            helper.setTo(emailBean.getToEmail());
            helper.setSubject(emailBean.getSubject());
            helper.setText(emailBean.getText(), true);
        } catch (MessagingException e) {
            System.out.println("==邮件发送失败"+ e.getMessage());
            return R.error();
        }
        try {
            javaMailSender.send(mimeMessage);
//            log.info("==邮件发送成功, Subject: {}, setTo:{}", emailBean.getSubject(), emailBean.getToEmail());
            return R.ok();
        } catch (Exception e) {
//            log.error("==邮件发送失败", e);
        }
        return R.error();
    }

}
